package edu.wayne.cs.csc4110.hw6.framework.plugin;

import edu.wayne.cs.csc4110.hw6.framework.GameScreen;
import edu.wayne.cs.csc4110.hw6.interfaces.plugin.PluginLoop;

public class GamePluginLoop extends Thread implements PluginLoop {

	private final ActivePlugin plugin;
	private final GameScreen screen;

	private boolean stopped = false;
	private boolean paused = false;

	public GamePluginLoop(ActivePlugin plugin, GameScreen screen) {
		this.plugin = plugin;
		this.screen = screen;
	}

	public ActivePlugin getPlugin() {
		return plugin;
	}

	@Override
	public void pausePlugin() {
		paused = true;
	}

	@Override
	public void resumePlugin() {
		paused = false;
	}

	@Override
	public void stopPlugin() {
		stopped = true;
	}

	@Override
	public void run() {

		plugin.onStart();
		while (true) {
			while (!plugin.isOver() && !stopped) {
				
				if (!paused) {
					screen.requestFocus();
					plugin.update();
					screen.repaint();
				}
				try {
					Thread.sleep(plugin.getDelay());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			screen.repaint();
			plugin.onFinish();
		}

	}

	public void restart() {
		plugin.restart();
		this.stopped = false;
		this.paused = false;

	}

	@Override
	public boolean isPluginPaused() {
		return this.paused;
	}

	@Override
	public boolean isPluginStopped() {
		return this.stopped;
	}

}
